package com.diligent.cloud.sfc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.canny.commons.model.Codes;
import com.canny.commons.model.ListResult;
import com.canny.commons.model.ObjectResult;
import com.canny.commons.model.Result;
import com.diligent.cloud.primary.data.feign.service.imat.IMatImageFeignService;
import com.diligent.cloud.sfc.model.CappCraftData;
import com.diligent.cloud.sfc.service.CraftDataService;
import com.diligent.cloud.web.utils.Converter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.Field;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

/**
 * CraftDataServiceImpl class
 *
 * @author xf107278
 * @date 3/30/2020
 */
@Service
public class CraftDataServiceImpl implements CraftDataService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private final String soaRequestUrl = "http://172.16.35.207:2020/";

    private final RestTemplate restTemplate;
    private final IMatImageFeignService iMatImageFeignService;
    private  final  int  MAX_ATTEMPTS = 3;

    public CraftDataServiceImpl(RestTemplate restTemplate, IMatImageFeignService iMatImageFeignService) {
        this.restTemplate = restTemplate;
        this.iMatImageFeignService = iMatImageFeignService;
    }

    @Override
    @Retryable(value = Exception.class, maxAttempts = MAX_ATTEMPTS, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public ResponseEntity<Result> getElineRuntimeParams(String machCode, String deviceType) throws Exception {
        String requestUrl = String.format(soaRequestUrl + "get_eline_runtime_params/%s/%s", machCode, deviceType);
        try {
            ObjectResult result = restTemplate.getForObject(requestUrl, ObjectResult.class);
            if (result.getCode() == 1) {
               result.modifyCode(Codes.success.getCode(), Codes.success.getMsg());
            }  else {
                result.modifyCode(Codes.fail.getCode(), Codes.fail.getMsg());
            }
            return ResponseEntity.ok(result);

        }catch (HttpClientErrorException httpClientErrorException){
            getElineName();
            throw new Exception();
        }
    }

    @Override
   @Retryable(value = Exception.class, maxAttempts = MAX_ATTEMPTS, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public ResponseEntity<ListResult> getElineEventTable(String machCode, String timeEnd, String duration) throws Exception {

        String requestUrl = String.format(soaRequestUrl + "get_eline_event_table/%s/%s/%s", machCode, timeEnd,
                duration);
        try {
            ListResult result = restTemplate.getForObject(requestUrl, ListResult.class);
            if (result.getCode() == 1) {
                result.modifyCode(Codes.success.getCode(), Codes.success.getMsg());
            } else {
                result.modifyCode(Codes.fail.getCode(), Codes.fail.getMsg());
            }
            return ResponseEntity.ok(result);
        }catch (HttpClientErrorException httpClientErrorException){
            getElineName();
            throw new Exception();
        }
    }

    @Override
    public ResponseEntity<ObjectResult> getCraftDataResource(String machCode, Principal principal) {
        CappCraftData cappCraftData = new CappCraftData();
        Field[] declaredFields = CappCraftData.class.getDeclaredFields();
        for (Field field : declaredFields) {
            try {
                field.setAccessible(true);
                Object cast = Converter.cast("--",
                        field.getType());
                field.set(cappCraftData, cast);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return ResponseEntity.ok(new ObjectResult(JSONObject.parse(JSONObject.toJSONString(cappCraftData))));
    }

    @Override
    public ResponseEntity<ObjectResult<String>> getItemIdByMatCode(String matCode) {
        return iMatImageFeignService.getItemIdByMatCode(matCode);
    }

    @Override
    public ObjectResult setMouldId(String matCode, String woOrder) {
        String token = "at.38s4iyczacw2eet7b3beevbgl912t0pz1-2rsetdrwx6-1xeqgcb-fvpvhhoev";
        String requestUrl = soaRequestUrl + "set_mould_id";
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("access_token", token);
        paramsMap.put("mid", matCode);
        paramsMap.put("mesid", woOrder);

        return  restTemplate.getForObject(requestUrl, ObjectResult.class, paramsMap);
    }

    public void getElineName() {
        String requestUrl = String.format(soaRequestUrl + "get_eline_name/%s", "at.38s4iyczacw2eet7b3beevbgl912t0pz1-2rsetdrwx6-1xeqgcb-fvpvhhoev");
        ObjectResult result = restTemplate.getForObject(requestUrl, ObjectResult.class);
        logger.error("401故障,重新获取token");
        if (result.getCode()!=1){
            logger.error("重新获取token失败");
        }
    }


}
